<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="74px">
        <el-form-item label="点检周期">
          <el-select
            v-model="searchParam.sopStandardCycleCode"
            placeholder="请选择点检周期"
            clearable
            style="width: 100%"
            @change="periodChange"
          >
            <el-option
              v-for="item in periodList"
              :key="item.itemCode"
              :label="item.itemName"
              :value="item.itemCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="点检标准">
          <el-select
            v-model="searchParam.sopStandardId"
            placeholder="请选择点检标准"
            clearable
            style="width: 100%"
            :disabled="!searchParam.sopStandardCycleCode"
          >
            <el-option
              v-for="item in standardList"
              :key="item.id"
              :label="item.standardName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="点检计划">
          <el-input
            v-model="searchParam.planNo"
            placeholder="请输入计划名称或编号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="点检设备">
          <el-input
            v-model="searchParam.assetCode"
            placeholder="请输入设备名称或编号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="reset">
            <i-ep-refresh />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()">
          <i-ep-plus />
          新增
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="handleTableDelete()"
        >
          <i-ep-delete />
          删除
        </el-button>
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
        @sort-change="onTableSortChanged"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="计划编号"
          prop="planNo"
          min-width="120"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          label="计划名称"
          prop="planName"
          min-width="220"
          align="left"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          label="点检周期"
          prop="taskPeriod"
          min-width="120"
          align="right"
          show-overflow-tooltip
          sortable
        >
          <template #default="scope">
            {{ scope.row.taskPeriod }}
            {{ useDictionary("TaskPeriodUnit", scope.row.taskPeriodUnit) }}
          </template>
        </el-table-column>
        <el-table-column
          label="点检时间(小时)"
          prop="planInspectionTime"
          min-width="160"
          align="right"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          label="计划起始日期"
          prop="planStartDate"
          min-width="140"
          show-overflow-tooltip
          align="center"
          sortable
        >
          <template #default="scope">
            {{ dayjs(scope.row.planStartDate).format("YYYY-MM-DD") }}
          </template>
        </el-table-column>
        <el-table-column
          label="计划截止日期"
          prop="planEndDate"
          min-width="140"
          align="center"
          show-overflow-tooltip
          sortable
        >
          <template #default="scope">
            {{ dayjs(scope.row.planEndDate).format("YYYY-MM-DD") }}
          </template>
        </el-table-column>
        <el-table-column
          label="是否启用"
          prop="enabled"
          min-width="120"
          show-overflow-tooltip
          align="center"
          sortable
        >
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.enabled === 1">启用</el-tag>
            <el-tag type="info" v-else>停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="备注"
          prop="remarks"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column fixed="right" label="操作" width="300" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openBuildDialog(scope.row)"
            >
              <i-ep-position />
              生成点检单
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="openOrdersDetail(scope.row)"
            >
              <i-ep-tickets />
              点检记录
            </el-button>

            <el-dropdown class="ml-[12px] align-middle!">
              <span
                class="el-dropdown-link text-[12px] c-[#409eff] cursor-pointer"
              >
                更多
                <i-ep-arrow-down size="10" class="text-[10px]! ml-[3px]!" />
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="openDialogdetail(scope.row)"
                    >查看</el-dropdown-item
                  >
                  <el-dropdown-item @click="openDialog(scope.row)"
                    >编辑</el-dropdown-item
                  >
                  <el-dropdown-item @click="deleteItem(scope.row.id)"
                    >删除</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <equAccuracyInspectionPlan-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
    <equAccuracyInspectionPlan-build
      v-model:visible="buildDialog.visible"
      :id="buildDialog.id"
      @echo-info="changeBuildVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import dayjs from "dayjs";
import router from "@/router";
import { filterOrder } from "@/utils/commonHooks";
defineOptions({
  name: "EAMEQUEQUACCURACYINSPECTIONPLAN",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/eam/equPrecisionCheckPlan/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = reactive({
  sort: {
    column: "",
    orderBy: "",
  },
});

// 初始化搜索参数数据
const searchParamInit = {
  sopTypeCode: "EquipPrecisionInspect",
  planNo: "",
  assetCode: "",
  sopStandardCycleCode: "",
  sopStandardId: "",
};

const deleteParam = {
  api: "/eam/equPrecisionCheckPlan/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {
  setTimeout(function () {}, 10);
}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

// 排序
// 监听表格排序方法
function onTableSortChanged(column: any) {
  const { prop, order } = column;
  console.log(prop, order);

  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };
}
// 监听页面 initParam 改化，重新获取表格数据
watch(() => initParam, getTableList, { deep: true });
onMounted(() => {
  getTableList();
});

// 定义生成点检单弹窗
const buildDialog = reactive<DialogOption>({
  visible: false,
  id: "",
});

// 打开生成点检单弹窗
function openBuildDialog(roleObj?: any) {
  if (roleObj) {
    buildDialog.visible = true;
    buildDialog.id = roleObj.id;
  }
}

// 点检记录页面跳转
function openOrdersDetail(row: any) {
  router.push({
    name: "EAMTEEQUIPPRECISIONPOINTCHECK",
    query: {
      planId: row.id,
    },
  });
}

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/eam/equPrecisionCheckPlan/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开巡检计划表单弹窗 */
function openDialog(roleObj?: any) {
  if (roleObj) {
    addDialog.title = "修改设备精度点检计划";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增设备精度点检计划";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开巡检计划表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "设备精度点检计划详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  buildDialog.visible = value;
  if (!value) {
    addDialog.data = {};
    buildDialog.data = {};
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await request({
      url: `/eam/equPrecisionCheckPlan/deleteItem/${id}`,
      method: "post",
    }).then((res) => {
      ElMessage.success("删除成功");
      search();
    });
  });
}

// 周期list
const periodList = ref(<any>[]);
async function getPeriods() {
  request({
    url: `/eam/equPrecisionCheckPlan/getCheckPeriods`,
    method: "get",
  })
    .then((data) => {
      if (data.data) {
        periodList.value = data.data || [];
      }
    })
    .catch((res) => {
      console.log(res);
    });
}
function periodChange(code: any) {
  searchParam.value.sopStandardId = "";
  if (code) {
    getStandardList(code);
  } else {
    standardList.value = [];
  }
}

// 点检标准list
const standardList = ref(<any>[]);
async function getStandardList(id: string) {
  request({
    url: `/eam/equPrecisionCheckPlan/getStandardList/${id}`,
    method: "get",
  })
    .then((data) => {
      if (data.data) {
        console.log("standardList.value", standardList.value);
        standardList.value = data.data || [];
      }
    })
    .catch((res) => {
      console.log(res);
    });
}

function changeBuildVisible() {}

onMounted(() => {
  getPeriods();
});
</script>
